import { TEAMS } from './consts';
import React, { memo, useState, useRef } from 'react';
import { IconFont, JumpIcon } from 'tdesign-icons-react';
import { BrowserRouterProps } from 'react-router-dom';
import { Row, Col, Button, List, Card, Tag, Link, Space, Dialog, Form, Input, MessagePlugin, Descriptions } from 'tdesign-react';
import DarkFullHISTLogo from 'assets/image/dark-logo-max-hist.png';
import LightFullHISTLogo from 'assets/image/light-logo-max-hist.png';
import styles from './index.module.less';
import store, { useAppSelector, useAppDispatch } from '@/modules/store';
import { selectGlobal } from '@/modules/global';
import DirectLink from './components/DirectLink';
import { DIRECT_LINKS } from './components/DirectLink/schoolCar';
import DescriptionsItem from 'tdesign-react/es/descriptions/DescriptionsItem';

const { ListItem } = List;
const { FormItem } = Form;

const User: React.FC<BrowserRouterProps> = () => {
  const globalState = useAppSelector(selectGlobal);
  const dispatch = useAppDispatch();
  const [visibleBtn, setVisibleBtn] = useState(false);
  const [formData, setFormData] = useState({ phone: '', email: '' });
  const formRef = useRef();
  const userData = store.getState().user.data;
  const { name: userName, studentId, gender, phone, email, role, department: { name: departmentName } } = userData;

  const handleBtnClose = () => {
    setVisibleBtn(false);
  };

  const handleBtnClick = () => {
    // 初始化表单数据
    setFormData({
      phone,
      email
    });
    setVisibleBtn(true);
  };

  const handleBtnConfirm = () => {
    (formRef.current as any)?.validate?.().then(async (result: boolean) => {
      if (result === true) {
        // 更新用户数据
        const newUserData = {
          ...userData,
          phone: formData.phone,
          email: formData.email
        };
        console.log(newUserData);

        // // 更新Redux状态
        // dispatch(setUserInfo({ data: newUserData }));

        // // 更新本地存储
        // await localforage.setItem('HIST-userInfo', newUserData);

        MessagePlugin.success('个人信息修改成功');
        setVisibleBtn(false);
      }
    });
  };
  // 表单字段变化处理函数
  const handleFormChange = (val: string, { name }: { name: string; }) => {
    setFormData(prev => ({
      ...prev,
      [name]: val
    }));
  };
  return (
    <>
      <Row gutter={[16, 16]} style={{ marginRight: 0 }}>
        <Col xs={12} lg={12} xl={9}>
          <Card className={styles.welcome} bordered={false} >
            <Row justify='space-between'>
              <Col className={styles.name}>
                <span className={styles.regular}>Hi~，今天是你加入科院的第 100 天～</span>
              </Col>
              <Col>
                <img alt='logo' src={globalState.theme === 'dark' ? DarkFullHISTLogo : LightFullHISTLogo} className={styles.logo} />
              </Col>
            </Row>
          </Card>
          <Card
            className={styles.userinfo}
            title='个人信息'
            bordered={false}
            actions={
              <>
                <Button shape='square' theme='default' variant='text' onClick={handleBtnClick}>
                  <IconFont name='edit' />
                </Button>
                <Dialog
                  header="个人信息修改"
                  visible={visibleBtn}
                  confirmBtn="我要改！"
                  cancelBtn="算了吧~"
                  onClose={handleBtnClose}
                  onConfirm={handleBtnConfirm}
                  body={
                    <>
                      <Form ref={formRef} style={{ paddingBottom: 0 }}>
                        <FormItem
                          label="手机号码"
                          name="phone"
                          initialData={formData.phone}
                          rules={[{ required: true, message: '手机号不能为空', type: 'error' },
                          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', type: 'error' }]}
                        >
                          <Input
                            value={formData.phone}
                            onChange={(val) => handleFormChange(val, { name: 'phone' })}
                            placeholder="请输入手机号码"
                          />
                        </FormItem>
                        <FormItem
                          label="邮箱地址"
                          name="email"
                          initialData={formData.email}
                          rules={[{ required: true, message: '邮箱不能为空', type: 'error' },
                          { pattern: /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱地址', type: 'error' }]}
                        >
                          <Input
                            value={formData.email}
                            onChange={(val) => handleFormChange(val, { name: 'email' })}
                            placeholder="请输入邮箱地址"
                          />
                        </FormItem>
                      </Form>
                      <Descriptions>
                        <DescriptionsItem label="如果需要修改更多信息，请联系管理员">
                        </DescriptionsItem>
                      </Descriptions>
                    </>}
                >

                </Dialog>
              </>
            }
          >
            <Row gutter={[16, 16]}>
              <Col span={3}>
                <div className={styles.label}>姓名</div>
                <div className={styles.value}>{userName}</div>
              </Col>
              <Col span={3}>
                <div className={styles.label}>性别</div>
                <div className={styles.value}>{gender === "male" ? '男' : gender === "female" ? "女" : "其他"}</div>
              </Col>
              <Col span={3}>
                <div className={styles.label}>手机</div>
                <div className={styles.value}>+86 {phone}</div>
              </Col>
              <Col span={3}>
                <div className={styles.label}>邮箱</div>
                <div className={styles.value}>{email}</div>
              </Col>
            </Row>
            <Row gutter={[16, 16]}>
              <Col span={3}>
                <div className={styles.label}>所属单位</div>
                <div className={styles.value}>{departmentName}</div>
              </Col>
              <Col span={3}>
                <div className={styles.label}>身份</div>
                <div className={styles.value}>{role === "student" ? '研究生' : role === "teacher" ? "教师" : "管理员"}</div>
              </Col>
              <Col span={3}>
                <div className={styles.label}>学/工号</div>
                <div className={styles.value}>{studentId}</div>
              </Col>
            </Row>
          </Card>
          <Card className={styles.statistics} style={{ padding: "0rem 0rem .0625rem 0rem" }} title='校园直通车' bordered={false}>
            <Space>
              {DIRECT_LINKS.map((link) => (
                <DirectLink
                  key={link.content}
                  content={link.content}
                  href={link.href}
                  image={link.image}
                  alt=''
                />
              ))}
            </Space>
          </Card>
        </Col>
        <Col xs={12} lg={12} xl={3}>
          <Card className={styles.postmsg}>
            <div className={styles.avatar}>
              <span>T</span>
            </div>
            <div className={styles.name}>{userName}</div>
            <div className={styles.position}>河南科技学院/{departmentName}</div>
          </Card>
          <Card
            className={styles.teams}
            bordered={false}
            title='最近预约记录'
            actions={
              <Link theme="primary" hover="color" prefixIcon={<JumpIcon />}>
                查看更多
              </Link>
            }
          >
            <List split={false}>
              {TEAMS.map((item) => (
                <ListItem key={item.id} action={
                  (() => {
                    switch (item.status) {
                      case 'approved':
                        return (
                          <Tag theme="success" variant="outline">
                            预约成功
                          </Tag>
                        );
                      case 'pending':
                        return (
                          <Tag theme="warning" variant="outline">
                            预约中
                          </Tag>
                        );
                      case 'rejected':
                        return (
                          <Tag theme="danger" variant="outline">
                            已拒绝
                          </Tag>
                        );
                      default:
                        return (
                          <Tag theme="default" variant="outline">
                            未知状态
                          </Tag>
                        );
                    }
                  })()}
                >
                  {item.floor}楼{item.roomNumber}室
                </ListItem>
              ))}
            </List>
          </Card>
        </Col>
      </Row >
    </ >
  );
};

export default memo(User);
